package com.jg.poiet.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtils {

    private final static DateFormat DATE_FORMAT1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private final static DateFormat DATE_FORMAT2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    private final static DateFormat DATE_FORMAT3 = new SimpleDateFormat("yyyy-MM-dd");
    private final static DateFormat DATE_FORMAT4 = new SimpleDateFormat("yyyy/MM/dd");

    /**
     * 获取当前日期
     * @param format    日期格式
     * @return  当前日期
     */
    public static String getNowDate(String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date());
    }

    /**
     * 解析日期
     */
    public static Date parseDate(String dateStr, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return sdf.parse(dateStr);
        } catch (Exception ignore) {}
        return null;
    }

    /**
     * 解析日期
     */
    public static Date parseDate(String dateStr) {
        if (dateStr == null || dateStr.length() == 0) {
            return null;
        }
        if (dateStr.contains("-")) {
            try {
                return DATE_FORMAT1.parse(dateStr);
            } catch (Exception ignore) {}
            try {
                return DATE_FORMAT3.parse(dateStr);
            } catch (Exception ignore) {}
        } else {
            try {
                return DATE_FORMAT2.parse(dateStr);
            } catch (Exception ignore) {}
            try {
                return DATE_FORMAT4.parse(dateStr);
            } catch (Exception ignore) {}
        }
        return null;
    }

    /**
     * 输出当前日期
     */
    public static void printNowDate(String note) {
        System.out.println(note+":"+getNowDate("yyyy-MM-dd HH:mm:ss SSS"));
    }

}
